//
//  TWCRefreshControl.swift
//  HMWeibo08
//
//  Created by 唐万超 on 15/8/6.
//  Copyright © 2015年 唐万超. All rights reserved.
//

import UIKit

// 下拉刷新的偏移量，超出之后，翻转动画
private let kTWCRefreshPullOffset: CGFloat = -60

// 下拉刷新控件，在tableView中
class TWCRefreshControl: UIRefreshControl {
    // 重写endRefreshing
    override func endRefreshing() {
        super.endRefreshing()
        twcRefreshView.endLoading()
    }

    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
       // print(frame)
        if (frame.origin.y > 0) {
            return
        }
        
        // KVO监听属性变化，判断是否刷新
        if refreshing {
            twcRefreshView.startLoading()
        }
        
        if frame.origin.y < kTWCRefreshPullOffset && !twcRefreshView.rotateFlag {
            print("翻上去")
            twcRefreshView.rotateFlag = true
        } else if frame.origin.y > kTWCRefreshPullOffset && twcRefreshView.rotateFlag {
            print("转下来")
            twcRefreshView.rotateFlag = false
        }
        
    }
    
    override init() {
    
        super.init()
 
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // KVO一定要移除
    deinit {
        self.removeObserver(self, forKeyPath: "frame")
    }
    
    // 设置UI
    private func setupUI() {
        
        // KVO监听属性变化
        self.addObserver(self, forKeyPath: "frame", options: NSKeyValueObservingOptions(rawValue: 0), context: nil)
        
        // 取消系统自带的小菊花
        tintColor = UIColor.clearColor()
    
        addSubview(twcRefreshView)
        
        // 设置布局
        twcRefreshView.ff_AlignInner(type: ff_AlignType.CenterCenter, referView: self, size: twcRefreshView.bounds.size)
    }
    
    // MARK: - 懒加载控件
    private lazy var twcRefreshView: TWCRefreshView = TWCRefreshView.loadRefreshView()

}

// 刷新视图，负责显示和动画
class TWCRefreshView: UIView {
    /// 旋转标记
    private var rotateFlag = false {
        didSet {
            // 当旋转则开始动画
            rotateTipIcon()
        }
    }
    
    // 加载图标
    @IBOutlet weak var loadIcon: UIImageView!
    @IBOutlet weak var tipView: UIView!
    @IBOutlet weak var tipIcon: UIImageView!
    
    /// 图标旋转动画
    private func rotateTipIcon() {
        
        let angle = rotateFlag ? CGFloat(M_PI + 0.01) : CGFloat(M_PI - 0.01)
        
        UIView.animateWithDuration(0.25) { () -> Void in
            
            self.tipIcon.transform = CGAffineTransformRotate(self.tipIcon.transform, angle)
            
        }
        
    }
    
    
    
    /// 开始加载动画
    private func startLoading() {
        
        // 判断如果当前有动画，则返回不执行
        if loadIcon.layer.animationForKey("loadIconAnim") != nil {
            return
        }

        tipView.hidden = true
        
        let anim = CABasicAnimation(keyPath: "transform.rotation")
        
        anim.toValue = 2 * M_PI
        anim.repeatCount = MAXFLOAT
        anim.duration = 1.0
        
        // 添加动画
        loadIcon.layer.addAnimation(anim, forKey: "loadIconAnim")
        
    }
    
    /// 结束动画
    private func endLoading() {
        tipView.hidden = false
        
        loadIcon.layer.removeAllAnimations()
    }

    // 加载xib中视图
    class func loadRefreshView() -> TWCRefreshView {
    
       return NSBundle.mainBundle().loadNibNamed("TWCRefreshView", owner: nil, options: nil) .last as! TWCRefreshView
    }
    
}
